<template>
  <el-card>
    <div class="card-wrap">
      <el-page-header @back="goBack" content="月度支出填报"> </el-page-header>
      <div>
        <div v-if="currentMode === 'add' || currentMode === 'edit'">
          <el-button @click="goBack">取消</el-button>
          <el-button
            v-if="!route.query.instanceId"
            type="primary"
            @click="handleSave"
            >保存</el-button
          >
          <el-button type="primary" @click="handleSubmit">提交</el-button>
        </div>

        <!-- <div v-if="currentMode === 'approve'">
          <el-button @click="goBack">取消</el-button>
       
          <template v-if="nodeId != 'ACT_010'">
            <el-button
              type="primary"
              :loading="model.saveLoading"
              @click="handleReject"
              >驳回</el-button
            >
          </template>
          <el-button
            type="primary"
            :loading="model.saveLoading"
            @click="handleSubmit('agree')"
            >通过</el-button
          >
        </div> -->
      </div>
    </div>
  </el-card>

  <br />
  <el-card>
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="140px"
      class="demo-ruleForm"
      :disabled="currentMode !== 'add' && currentMode !== 'edit'"
    >
      <el-row>
        <el-col :xl="8" :lg="12">
          <el-form-item label="填报人" prop="name">
            <el-input v-model="ruleForm.name" disabled />
          </el-form-item>
        </el-col>
        <el-col :xl="8" :lg="12">
          <el-form-item label="单位名称" prop="code">
            <el-cascader
              ref="cascader"
              style="width: 100%"
              popper-class="dept-cas"
              v-model="ruleForm.happenDeptCode"
              clearable
              filterable
              :options="joinDeptList"
              :props="model.defaultProps"
              placeholder="输入名称搜索"
              @change="handleDeptChange"
            />
          </el-form-item>
          <!-- <el-form-item label="填报单位" prop="happenDept">
            <el-select
              style="width: 100%"
              v-model="ruleForm.happenDept"
              placeholder="请选择填报单位"
              class="custom-select-width"
            >
              <el-option
                v-for="item in deptOptions"
                :label="item"
                :value="item"
                :key="item"
              />
            </el-select>
          </el-form-item> -->
        </el-col>
      </el-row>

      <el-row>
        <el-col :xl="8" :lg="12">
          <el-form-item label="填报月份" prop="happenMonth">
            <el-date-picker
              v-model="ruleForm.happenMonth"
              type="month"
              style="width: 100%"
              format="YYYY-MM"
              value-format="YYYY-MM"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :xl="8" :lg="12">
          <el-form-item label="填报类型" prop="fillCategory">
            <el-select
              style="width: 100%"
              v-model="ruleForm.fillCategory"
              placeholder="请选择填报单位"
              class="custom-select-width"
            >
              <el-option label="项目类" value="1" />
              <el-option label="非项目类" value="2" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="ruleForm.fillCategory === '1'">
        <el-col :xl="8" :lg="12">
          <el-form-item label="填报项目" prop="projectId">
            <el-select
              style="width: 100%"
              v-model="ruleForm.projectId"
              clearable
              placeholder="请选择"
              value-key="id"
              @change="handleSelected"
            >
              <el-option
                v-for="item in projectList"
                :key="item.id"
                :label="item.projectName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xl="8" :lg="12">
          <el-form-item label="项目编号">
            <el-input disabled v-model.trim="ruleForm.projectNum"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-else>
        <el-col :xl="8" :lg="12">
          <el-form-item label="填报事项说明" prop="ext1">
            <el-input
              v-model="ruleForm.ext1"
              type="textarea"
              :rows="2"
              placeholder="请输入填报事项说明"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- <el-row>
        <el-col :span="10">
          <el-form-item label="经费审批类型" prop="approvalTypeCode">
            <el-select
              v-model="ruleForm.approvalTypeCode"
              placeholder="请选择经费审批类型"
              class="custom-select-width"
              value-key="dicCode"
            >
              <el-option
                v-for="item in approvalTypeList"
                :label="item.dicValue"
                :value="item"
                :key="item.dicCode"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row> -->
      <el-row v-if="currentMode == 'add' || currentMode === 'edit'">
        <el-col :span="20">
          <el-form-item label="导入月度支出" prop="files">
            <el-upload
              name="uploadFile"
              multiple
              :accept="acceptTypes"
              :action="uploadComUrl"
              :headers="uploadHeaders"
              :on-success="handleSuccess"
              :on-remove="handleRemove"
              :on-error="handleError"
              :file-list="defaultFileList"
              :before-upload="beforeAvatarUpload"
              :on-preview="handlePreview"
            >
              <el-tooltip class="item" effect="dark" content="月度支出请填写单位为万元的数值" placement="top">
                <el-button size="small" type="primary">导入</el-button>
              </el-tooltip>
              <span v-if="ruleForm.fillCategory === '1'">
                请下载 &nbsp;<el-link
                  @click="
                    postXlsxDownload('项目月度支出表(项目团队填写)-模版.xlsx')
                  "
                  type="primary"
                  >项目月度支出表(项目团队填写)-模版.xlsx</el-link
                >&nbsp;后点击导入
              </span>
              <span v-else>
                请下载 &nbsp;<el-link
                  @click="postXlsxDownload('非项目月度支出表-模版.xlsx')"
                  type="primary"
                  >非项目月度支出表-模版.xlsx</el-link
                >&nbsp;后点击导入
              </span>
              <!-- <span style="color: red; margin-left: 10px; font-size: 14px">请注意：填报金额单位为 元（人民币）。</span> -->
            </el-upload>
            <!-- <el-button type="primary">导入</el-button> -->
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <br />
    <el-table
      :data="tableData"
      border
      style="width: 100%"
      :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
    >
      <el-table-column prop="subject" align="center" label="经费类别">
      </el-table-column>
      <el-table-column
        prop="spendAmount"
        label="月度支出（万元，人民币）"
        align="center"
      >
      </el-table-column>
    </el-table>
  </el-card>
  <br />
  <el-card v-if="route.query.instanceId">
    <template #header>
      <div class="card-box-header">
        <span> 流程状态</span>
      </div>
    </template>
    <div v-if="steps && steps.length">
      <el-collapse-transition>
        <status-info :currentStep="currentStep" :steps="steps" />
      </el-collapse-transition>
    </div>
  </el-card>
  <br />
  <el-card v-if="route.query.instanceId">
    <template #header>
      <div class="card-box-header">
        <span> 流转记录</span>
      </div>
    </template>
    <div>
      <el-collapse-transition>
        <approval-info :activities="approveRecord" />
      </el-collapse-transition>
    </div>
  </el-card>

  <approveDialog
    v-if="approveDialogVisiable"
    :nodeId="nodeId"
    :flowType="model.flowType"
    @cancel="cancel"
    @sure="sureSubmit"
  ></approveDialog>

  <rejectDialog
    v-if="rejectDialogVisiable"
    @cancel="cancel"
    @sure="sureRejectSubmit"
  ></rejectDialog>
</template>

<script lang="ts" setup>
import { useRouter, useRoute } from "vue-router";
import { reactive, toRefs, onMounted, ref, nextTick } from "vue";
// import { deptOptions } from "../enums/index";
import { storageLocal } from "/@/utils/storage";
import { useUpload } from "/@/hooks";
import { flowStatusObj } from "/@/components/StatusInfo/type";
import {
  importMonthForFunds,
  saveMonthForFunds,
  getInputDetail
} from "/@/api/funds";
import {
  flowStart,
  flowSubmit,
  flowReject,
  getApproveHistory,
  postProjectList
} from "/@/api/project";
import { postDictList } from "/@/api/common";
import NotifMessage from "/@/utils/message/notification";
import approveDialog from "/@/components/approveDialog/index.vue";
import rejectDialog from "/@/components/rejectDialog/index.vue";
import StatusInfo from "/@/components/StatusInfo/index.vue";
import ApprovalInfo from "/@/components/ApprovalInfo/index.vue";
import { postSysCompanyList } from "/@/api/organization";
import { postDeptList } from "/@/api/dept";

const ruleFormRef = ref<HTMLFormElement | null>(null) as any;
const router = useRouter();
const route = useRoute();
let joinDeptList = ref([]);
let projectList = ref([]);
const {
  handleError,
  beforeAvatarUpload,
  uploadComUrl,
  acceptTypes,
  uploadHeaders
} = useUpload();
const defaultFileList = ref([]);
const approvalTypeList = ref([]);
let approveDialogVisiable = ref<boolean>(false); // 点击提交弹窗，选择下一步审批人
let rejectDialogVisiable = ref<boolean>(false); // 点击驳回弹窗，选择下一步审批人
const nodeId = route.query.nodeId ? route.query.nodeId : "ACT_010";
const currentStep = ref(null);
const cascader = ref(null);
const steps = ref([]);

const approveRecord = ref([]);
const state = reactive({
  ruleForm: {
    name: "",
    projectId: null,
    projectNum: null,
    fillCategory: "1",
    projectName: null,
    ext1: "",
    happenDeptCode: null,
    // approvalTypeCode: null,
    approvalTypeName: "",
    happenDept: "",
    happenMonth: "",
    files: []
  },
  tableData: []
});

const model = reactive({
  flowType: "2027",
  approveHandlerId: null,
  saveLoading: false,
  approvalStep: "start",
  defaultProps: {
    children: "children",
    label: "deptDescShrt",
    value: "id",
    checkStrictly: true,
    emitPath: false
  }
});

//发起流程
const flowStartData = reactive({
  formBaseInfo: {
    billName: "",
    projectName: "",
    projectManageId: route.query.id,
    id: route.query.id,
    flowStartAttachmentArr: []
  },
  flowFormData: {
    businessId: route.query.id,
    flowTypeCode: "2027",
    nodeId: route.query.nodeId,
    projectManageId: route.query.id,
    remarks: "",
    saveState: "1"
  },
  formSubMap: {
    stageStatus: "32",
    flowType: "2027",
    assignee: null,
    opinion: ""
  }
});

//审批流程
const flowPassData = reactive({
  formBaseInfo: {
    id: route.query.id,
    acceptUsers: null
  },
  flowFormData: {
    approvalComments: "",
    approvalResult: "",
    businessId: route.query.id,
    flowId: route.query.flowId,
    flowTypeCode: "2027",
    instanceId: route.query.instanceId,
    nodeId: route.query.nodeId,
    remarks: "",
    saveState: "1"
  },
  formSubMap: {
    stageStatus: "32",
    flowType: "2027",
    nodeId: route.query.nodeId,
    procInstId: route.query.instanceId,
    taskId: route.query.taskId,
    opinion: "",
    assignee: null,
    isChargehand: "1", //1：向下提交到下一步：0：回退到某一步
    specialReject: "0"
  },
  tmpStorage: {
    nodeId: route.query.nodeId,
    flowId: route.query.flowId,
    taskId: route.query.taskId,
    handlerId: null,
    valueJson: ""
  }
});

const flowRejectData = reactive({
  formRejectMap: {
    procInstId: route.query.instanceId,
    nodeId: route.query.nodeId,
    taskId: route.query.taskId,
    opinion: ""
  }
});

const rules = reactive({
  name: [
    {
      required: true,
      message: "",
      trigger: "blur"
    }
  ],
  happenDept: [
    {
      required: true,
      message: "请选择填报单位",
      trigger: "change"
    }
  ],
  fillCategory: [
    {
      required: true,
      message: "请选择项目类型",
      trigger: "change"
    }
  ],
  projectId: [
    {
      required: true,
      message: "请选择填报项目",
      trigger: "change"
    }
  ],
  happenMonth: [
    {
      required: true,
      message: "请选择填报月份",
      trigger: "change"
    }
  ],
  // approvalTypeCode: [
  //   {
  //     required: true,
  //     message: "请选择经费审批类型",
  //     trigger: "change"
  //   }
  // ],
  files: [
    {
      required: true,
      message: "请导入当月科研经费",
      trigger: "change"
    }
  ],
  ext1: [
    {
      required: true,
      message: "请输入填报事项说明",
      trigger: "change"
    }
  ]
});

const { ruleForm, tableData } = toRefs(state);

const handleDeptChange = () => {
  const selected = cascader.value.getCheckedNodes();
  if (selected.length > 0) {
    state.ruleForm.happenDeptCode = selected[0].data.id;
    state.ruleForm.happenDept = selected[0].data.deptDescShrt;
  }
};

const initDeptList = async () => {
  const { code, data } = await postDeptList({
    pageSize: 0
  });
  let deptList = [];
  if (code === 200) {
    deptList = data.map(item => {
      return {
        id: item.id,
        deptDescShrt: item.deptDescShrt,
        companyLegalName: item.companyLegalName,
        children: item.children
      };
    });
  }
  let companyList = [];
  const res = await postSysCompanyList({
    pageSize: 0
  });
  if (res.code === 200) {
    res.data.list.map(el => {
      companyList.push({
        id: el.id,
        companyLegalName: el.companyLegalName,
        deptDescShrt: el.companyName,
        isEmp: true
      });
    });
  }

  joinDeptList.value = [
    {
      deptDescShrt: "内部单位",
      disabled: true,
      children: deptList,
      id: "0-0"
    },
    {
      deptDescShrt: "外部单位",
      disabled: true,
      children: companyList,
      id: "0-1"
    }
  ];
};

const handleSelected = item => {
  const target = projectList.value.find(el => el.id === item);
  state.ruleForm.projectNum = target.projectCode;
  state.ruleForm.projectName = target.projectName;
};

// 获取项目信息
const getProjectList = async () => {
  try {
    const { code, data } = await postProjectList({ pageNum: 1, pageSize: 0 });
    if (code === 200) {
      projectList.value = data.list;
    }
  } catch (err) {
    console.log(err);
  }
};
const postXlsxDownload = name => {
  window.open(`${location.origin}${location.pathname}/${name}`);
};

const handleSuccess = (res, file) => {
  if (res.code === 200) {
    state.ruleForm.files = [file];
    defaultFileList.value = [file];
    importFile();
  }
};

const importFile = async () => {
  const { code, data } = await importMonthForFunds({
    deptName: state.ruleForm.happenDept,
    monthDate: state.ruleForm.happenMonth,
    fileUUid: defaultFileList.value[0].response.data.uuidFile
  });
  if (code === 200) {
    state.tableData = data;
  }
};

const handleRemove = (file, fileList, item) => {
  item.dFiles = fileList;
};

const initProjectApprovalTypeList = async () => {
  try {
    const params = {
      dicType: "rd_flow_type_budget"
    };
    const { code, data } = await postDictList(params);
    if (code === 200) {
      approvalTypeList.value = data;
    }
  } catch (err) {
    console.log(err);
  }
};

onMounted(() => {
  const info = storageLocal.getItem("rdms-info");
  state.ruleForm.name = info.name;
  // const arr = date.toLocaleDateString().split("/");
  // const currentDate = new Date();
  // const currentDay = currentDate.getDate();
  // const currentYear = currentDate.getFullYear();
  // const currentMonth = currentDate.getMonth();
  // if (currentDay > 8) {
  //   state.ruleForm.happenMonth = `${currentYear}-${currentMonth + 1}`;
  // } else {
  //   state.ruleForm.happenMonth = `${currentYear}-${currentMonth}`;
  // }

  // state.ruleForm.happenMonth = arr[0] + "-" + arr[1];
  const { query } = route;
  if (query.id) {
    getTableInfo(query.id);
  }
  if (query.instanceId) {
    getApproveHistoryList(query.instanceId);
    getStep();
  }
  // if (query.approvalTypeCode) {
  //   flowStartData.flowFormData.flowTypeCode = query.approvalTypeCode;
  //   flowStartData.formSubMap.flowType = query.approvalTypeCode;

  //   flowPassData.flowFormData.flowTypeCode = query.approvalTypeCode;
  //   flowPassData.formSubMap.flowType = query.approvalTypeCode;
  //   model.flowType = query.approvalTypeCode;
  //   state.ruleForm.approvalTypeCode = {
  //     dicCode: query.approvalTypeCode,
  //     dicValue: query.approvalTypeName
  //   };
  // }
  initDeptList();
  getProjectList();
  initProjectApprovalTypeList();
});

// const formatZero = (num, len) => {
//   if (String(num).length > len) {
//     return num;
//   }
//   return (Array(len).join(0) + num).slice(-len);
// };

const getTableInfo = async id => {
  const { query } = route;
  const { code, data } = await getInputDetail({
    inputId: id,
    inputType: "1"
  });
  if (code === 200) {
    let { inputDate, deptCode, inputUserName, deptName } = data;
    state.ruleForm.name = inputUserName || query.name;

    state.ruleForm.happenDept = deptName;
    state.ruleForm.happenDeptCode = deptCode;

    state.ruleForm.happenMonth = inputDate;
    state.ruleForm.projectId = data.projectId;
    state.ruleForm.projectNum = data.projectCode;
    state.ruleForm.projectName = data.projectName;
    state.tableData = data.data;
    state.ruleForm.fillCategory = data.fillCategory;
    state.ruleForm.ext1 = data.ext1;
  }
};

// const handleApprove = async () => {
//   const params = {
//     id: route.query.id
//   };
//   const { code, message } = await getInputApprove(params);
//   if (code === 200) {
//     NotifMessage.success(message);
//     goBack();
//   } else {
//     NotifMessage.error(message);
//   }
// };

// const handleReject = async () => {
//   const params = {
//     id: route.query.id
//   };
//   const { code, message } = await getInputReject(params);
//   if (code === 200) {
//     NotifMessage.success(message);
//     goBack();
//   } else {
//     NotifMessage.error(message);
//   }
// };

const goBack = () => {
  router.push({
    path: "/funds/statistics"
  });
};

const handleSave = async (flag = true, status = "1") => {
  {
    if (tableData.value.length > 0) {
      state.ruleForm.files = [{ name: "123" }];
      nextTick(() => {
        ruleFormRef.value.clearValidate("files");
      });
    }
    const isValid = await new Promise(resolve =>
      ruleFormRef.value.validate(resolve)
    );
    if (isValid) {
      const { code, data, message } = await saveMonthForFunds({
        inputId: route.query.id,
        happenDept: state.ruleForm.happenDept,
        happenDeptCode: state.ruleForm.happenDeptCode,
        happenMonth: state.ruleForm.happenMonth,
        spends: state.tableData,
        projectId: state.ruleForm.projectId,
        fillCategory: state.ruleForm.fillCategory,
        fillSaveStatus: status,
        ext1: state.ruleForm.ext1
      });
      if (code === 200) {
        flowStartData.formBaseInfo.projectManageId =
          state.ruleForm.projectId || data;
        flowStartData.formBaseInfo.projectName =
          state.ruleForm.projectName || "非项目类经费导入";
        flowStartData.formBaseInfo.id = data;
        flowStartData.flowFormData.businessId = data;
        flowStartData.flowFormData.projectManageId =
          state.ruleForm.projectId || data;
        if (flag) {
          goBack();
          return true;
        } else {
          return false;
        }
      } else {
        NotifMessage.error(message);
      }
    }
  }
};

// 点击提交，校验通过后，弹窗：选择下一节点处理人
const handleSubmit = async () => {
  model.saveLoading = true;
  if (tableData.value.length > 0) {
    state.ruleForm.files = [{ name: "123" }];
    nextTick(() => {
      ruleFormRef.value.clearValidate("files");
    });
  }
  const isValid = await new Promise(resolve =>
    ruleFormRef.value.validate(resolve)
  );
  model.saveLoading = false;
  if (isValid) {
    approveDialogVisiable.value = true;
  }
};

// 点击弹窗的确定后，保存、提交，单据往下流转
const sureSubmit = async params => {
  console.log("params", params);
  approveDialogVisiable.value = false;
  const flag = await handleSave(false, "2");
  if (flag !== false) return;
  if (route.query.instanceId) {
    passProcess(params);
  } else {
    startProcess(params);
  }
};

// 流程发起
const startProcess = async params => {
  const projectName =
    state.ruleForm.fillCategory === "1" ? state.ruleForm.projectName : "非项目";
  flowStartData.formBaseInfo.billName = `${projectName}-${state.ruleForm.happenMonth}-月度支出-审批流程`;
  flowStartData.flowFormData.remarks = params.remark;
  flowStartData.formSubMap.assignee = params?.handlederId?.id;
  // flowStartData.formSubMap.opinion = `备注:${params.remark}`;
  model.saveLoading = true;
  const { code, message } = await flowStart(flowStartData);
  if (code === 200) {
    NotifMessage.success(message);
    goBack();
  } else {
    NotifMessage.error(message);
  }
};

// 流程审批通过
const passProcess = async params => {
  flowPassData.flowFormData.approvalComments = params.remark;
  flowPassData.flowFormData.approvalResult = params.isApprove; //同意：1，不同意：0
  flowPassData.flowFormData.remarks = params.remark;
  flowPassData.formSubMap.opinion = `备注:${params.remark}#e#审批意见:${
    params.isApprove === "1" ? "同意" : "不同意"
  }`;
  flowPassData.tmpStorage.valueJson = JSON.stringify(flowPassData.formSubMap);
  const info = storageLocal.getItem("rdms-info");
  const userId = info?.userId;
  flowPassData.tmpStorage.handlerId = userId;
  flowPassData.formBaseInfo.acceptUsers = params?.handlederId?.id || userId;
  flowPassData.formSubMap.assignee = params?.handlederId?.id || userId;
  model.saveLoading = true;
  const { code, message } = await flowSubmit(flowPassData);
  if (code === 200) {
    NotifMessage.success(message);
    router.push("/approval/todo");
  } else {
    NotifMessage.error(message);
  }
};

//确定驳回(或者驳回指点节点)
const sureRejectSubmit = async params => {
  model.saveLoading = true;
  flowRejectData.formRejectMap.opinion = `#e#驳回意见:${params.remark}`;
  const { code, message } = await flowReject(flowRejectData);
  if (code === 200) {
    NotifMessage.success(message);
    goBack();
  } else {
    NotifMessage.error(message);
  }
};

//查询流程审批记录
const getApproveHistoryList = async instanceId => {
  const { code, data } = await getApproveHistory(instanceId);
  if (code === 200) {
    approveRecord.value = data;
  }
};

//关闭弹窗
const cancel = async () => {
  rejectDialogVisiable.value = false;
  approveDialogVisiable.value = false;
  model.saveLoading = false;
};

//获取流程转态
const getStep = () => {
  if (model.flowType) {
    steps.value = flowStatusObj[model.flowType];
  }
  if (steps.value && steps.value.length) {
    steps.value.forEach((item, index) => {
      if (item.nodeId === nodeId) {
        currentStep.value = Number(index);
      }
    });
  }
};

const currentMode = route.query.mode;
// const isAdd = route.query.mode === "add";
// const isLook = route.query.mode === "look" || route.query.mode === "approve";
// const isaApprove = route.query.mode === "approve";
</script>

<style lang="scss" scoped>
.card-wrap {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-box-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .header-btn {
    font-size: 14px;
    cursor: pointer;
  }
}

.custom-select-width {
  width: 100% !important;
}
</style>
